package org.pan.service;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.persist.Transactional;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.pan.bean.LoginUser;
import org.pan.bean.QLoginUser;

import javax.persistence.EntityManager;

@Singleton
@Transactional
public class SystemService {

    @Inject
    private Provider<EntityManager> entityManagerProvider;

    public void init() {
        EntityManager entityManager = entityManagerProvider.get();
        JPAQueryFactory jpaQueryFactory = new JPAQueryFactory(entityManager);
        LoginUser loginUser = jpaQueryFactory.selectFrom(QLoginUser.loginUser).where(QLoginUser.loginUser.username.eq("admin")).fetchOne();
        if (loginUser == null) {
            LoginUser loginUser1 = new LoginUser();
            loginUser1.setUsername("admin");
            loginUser1.setPassword("admin");
            entityManager.persist(loginUser1);
        }
    }

    public LoginUser login(String usernameText, String passwordText) {
        JPAQueryFactory jpaQueryFactory = new JPAQueryFactory(entityManagerProvider.get());
        QLoginUser loginUser = QLoginUser.loginUser;
        return jpaQueryFactory.selectFrom(loginUser).where(loginUser.username.eq(usernameText).and(loginUser.password.eq(passwordText))).fetchOne();
    }
}
